import { loadAllDistrict } from '@/api/modules/ax/district/district';
import type { AxDistrict } from '@/api/modules/ax/district/types';

export let districtTree: AxDistrict[] = [];

/**
 * @description: 转成树形结构
 * @param {AxDistrict} data
 */
const convertToTree = (data: AxDistrict[]): AxDistrict[] => {
  const map: { [key: string]: AxDistrict } = {};
  const tree: AxDistrict[] = [];

  // First pass - map each district by districtId
  data.forEach(item => {
    map[item.district] = {
      districtId: item.districtId,
      pid: item.pid,
      district: item.district,
      level: item.level,
      children: [],
    };
  });

  data.forEach(item => {
    const district = map[item.districtId];
    if (item.pid == '0') {
      tree.push(district);
    } else {
      const parent = map[item.pid];
      if (parent) {
        parent.children!.push(district);
      } else {
        // `Parent district ${item.pid} not found for district ${item.districtId}`;
      }
    }
  });

  return tree;
};
export const getDistrictTree = async (): Promise<AxDistrict[]> => {
  if (districtTree.length === 0) {
    const { data } = await loadAllDistrict();
    districtTree = convertToTree(data.rows);
  }
  return districtTree;
};
